package drds.configuration.db.transaction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;

/**
 * 本地连接事物管理容器. 注意本框架不支持嵌套事务即-事务[事务[]...].
 */
public class TransactionContext {
    public static Logger log = LoggerFactory.getLogger(TransactionContext.class);

    /**
     * 是否正在进行事物操作
     */
    private static ThreadLocal<Boolean> transactioning = new ThreadLocal<Boolean>();

    /**
     * dataSourceId
     */
    private static ThreadLocal<String> dataSourceId = new ThreadLocal<String>();
    /**
     * 数据库连接
     */
    private static ThreadLocal<Connection> connection = new ThreadLocal<Connection>();

    /**
     * <pre>
     * ============================================================
     * set操作
     * ============================================================
     * </pre>
     */
    public static final void set(Boolean transaction) {
        TransactionContext.transactioning.set(transaction);
    }

    public static void set(String groupDataSourceId) {
        TransactionContext.dataSourceId.set(groupDataSourceId);
    }

    public static final void set(Connection connection) {
        TransactionContext.connection.set(connection);
    }

    /**
     * <pre>
     * ============================================================
     * remove操作
     * ============================================================
     * </pre>
     */
    public static final void remove() {
        if (TransactionContext.transactioning.get() != null) {
            TransactionContext.transactioning.remove();
        }
        if (TransactionContext.dataSourceId.get() != null) {
            TransactionContext.dataSourceId.remove();
        }
        if (TransactionContext.connection.get() != null) {
            TransactionContext.connection.remove();
        }

    }

    /**
     * <pre>
     * ============================================================
     * get操作
     * ============================================================
     * </pre>
     */
    public static final boolean isTransactioning() {
        Boolean transactioning = TransactionContext.transactioning.get();
        return transactioning != null && transactioning == true;

    }

    public static final String getDataSourceId() {
        return TransactionContext.dataSourceId.get();
    }

    public static final Connection getConnection() {
        Connection connection = TransactionContext.connection.get();
        return connection;
    }


}
